package com.javiercp.ayudaapp.contacts;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.provider.Contacts.People.Phones;

@SuppressWarnings("deprecation")
public class ContactAccessorSDK3_4 extends ContactAccessor {

	@Override
	public Intent getPickContactIntent() {
		return new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
	}

	@Override
	public ContactInfo loadContact(ContentResolver contentResolver, Uri contactUri) {
        ContactInfo contactInfo = new ContactInfo();
        Cursor cursor = contentResolver.query(contactUri, new String[]{People.DISPLAY_NAME}, null, null, null);
        try {
            if (cursor.moveToFirst()) {
            	contactInfo.setContactID(-1);
                contactInfo.setDisplayName(cursor.getString(0));
                contactInfo.setContactUri(contactUri);
            }
        } finally {
            cursor.close();
        }
        
        return contactInfo;

	}

	@Override
	public ArrayList<ContactPhone> getContactPhones(ContentResolver contentResolver, ContactInfo contactInfo) {
		ArrayList<ContactPhone> retValue = new ArrayList<ContactPhone>();
		
        Uri phoneUri = Uri.withAppendedPath(contactInfo.getContactUri(), Phones.CONTENT_DIRECTORY);
        Cursor cursor = contentResolver.query(phoneUri, 
        		new String[]{Phones._ID, Phones.NUMBER, Phones.TYPE}, 
        		null, null, 
        		Phones.ISPRIMARY + " DESC");
        try {
        	while (cursor.moveToNext()) {        		     		
        		retValue.add(new ContactPhone(cursor.getString(cursor.getColumnIndex(Phones.NUMBER)), 
        				cursor.getString(cursor.getColumnIndex(Phones.TYPE))));
        	}
        } finally {
            cursor.close();
        }
        
        return retValue;
	}
	
	@Override
	public ArrayList<ContactEmail> getContactEmails(ContentResolver contentResolver, ContactInfo contactInfo) {
		ArrayList<ContactEmail> retValue = new ArrayList<ContactEmail>();
		
 		Cursor cursor = contentResolver.query( 
 				Contacts.ContactMethods.CONTENT_EMAIL_URI, 
 				new String[]{Phones._ID, Contacts.ContactMethods.DATA, Contacts.ContactMethods.CONTENT_EMAIL_TYPE}, 
 				Contacts.ContactMethods.PERSON_ID + " = ?", 
 				new String[]{Long.toString(contactInfo.getContactID())}, null); 
        try {
        	while (cursor.moveToNext()) {        		     		
        		retValue.add(new ContactEmail(cursor.getString(cursor.getColumnIndex(Contacts.ContactMethods.DATA)), 
        				cursor.getString(cursor.getColumnIndex(Contacts.ContactMethods.CONTENT_EMAIL_TYPE))));
        	}
        } finally {
            cursor.close();
        }
        
        return retValue;
	}
	
}
